package com.example.demo.controller;


import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.*;

import com.example.demo.service.*;
import com.example.demo.utils.DateUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;


import java.util.List;
import java.util.regex.Pattern;

/**
 * 简历表(Resume)表控制层
 *
 * @author makejava
 * @since 2023-12-12 20:16:59
 */
@RestController
@RequestMapping("resume")
public class ResumeController {

    /**
     * 服务对象
     */
    @Autowired
    private ResumeService resumeService;

    @Autowired
    private UserService userService;

    @Autowired
    private EducationExperienceService educationExperienceService;

    @Autowired
    private WorkExperienceService workExperienceService;

    /**
     * 简历信息
     *
     * @return 单条数据
     */
    @GetMapping("resumeInfo")
    public Result resumeInfo() {
        return Result.success(resumeService.selectByUserId(getUser().getId()));
    }

    /**
     * 获取用户
     *
     * @return {@code User}
     */
    private User getUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String account = JWT.decode(token).getAudience().get(0);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        return userService.getOne(wrapper);
    }



    /**
     * 分页查询所有简历
     *
     * @param current 当前
     * @param size    数量
     * @return 所有数据
     */
    @GetMapping("list")
    public Result list(Integer current, Integer size) {
        IPage<Resume> pageResult = resumeService.selectByPage(current, size);
        return Result.success(pageResult);
    }


    /**
     * 添加/编辑简历
     *
     * @return {@code String}
     */
    @PostMapping("doAdd")
    public Result doAdd(@RequestBody Resume resume) {
        String timestampPattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$";
        if (resume.getAge()!=null){
            if (Pattern.matches(timestampPattern, resume.getAge())) {
                String ageConvert= DateUtil.convertTime(resume.getAge());
                String age=DateUtil.getLife(ageConvert);
                resume.setAge(age);
            }
        }
        if (resume.getExperience()!=null){
            if (Pattern.matches(timestampPattern, resume.getExperience())) {
                String experienceConvert = DateUtil.convertTime(resume.getExperience());
                String experience = DateUtil.getLife(experienceConvert);
                resume.setExperience(experience);
            }
        }
        try {
            if (resume.getId() == null) {
                User user=getUser();
                resume.setUserId(user.getId());
                resumeService.save(resume);
                return Result.success("简历添加成功");

            } else {
                UpdateWrapper<Resume> wrapper=new UpdateWrapper<>();
                wrapper.eq("id",resume.getId());
                resumeService.update(resume,wrapper);
                return Result.success("简历编辑成功");
            }

        } catch (Exception e) {
            return Result.error("参数错误");
        }
    }

    /**
     * 个人优势添加/编辑
     *
     * @return {@code Result}
     */
    @PostMapping("advantage")
    public Result advantage(@RequestBody Resume resume){
        try {
            UpdateWrapper<Resume> wrapper=new UpdateWrapper<>();
            wrapper.eq("id",resume.getId());
            Resume res=resumeService.getOne(wrapper);
            res.setIntroduction(resume.getIntroduction());
            resumeService.update(res,wrapper);
            return Result.success("个人优势添加成功");
        }catch (Exception e){
            return Result.error("参数错误");

        }
    }


    /**
     * 上传头像
     *
     * @param file 文件
     * @param id   编号
     * @return {@code Result}
     */
    @PostMapping("uploadAvatar")
    public Result uploadAvatar(@RequestParam MultipartFile file, @RequestParam Integer id) {
        // 检查图片是否为空
        if (file.isEmpty()) {
            return Result.error("400", "请选择要上传的图片");
        }
        try {
            // 获取图片信息
            byte[] data = file.getBytes();
            Resume resume = resumeService.getById(id);
            resume.setAvatar(data);
            UpdateWrapper<Resume> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            resumeService.update(resume, wrapper);
            return Result.success("头像上传成功");
        } catch (Exception e) {
            return Result.error("头像传失败");
        }
    }

    /**
     * 上传二维码
     *
     * @param file 文件
     * @param id   编号
     * @return {@code Result}
     */
    @PostMapping("uploadQrcode")
    public Result uploadQrcode(@RequestParam MultipartFile file, @RequestParam Integer id) {
        // 检查图片是否为空
        if (file.isEmpty()) {
            return Result.error("400", "请选择要上传的图片");
        }
        try {
            // 获取图片信息
            byte[] data = file.getBytes();
            Resume resume = resumeService.getById(id);
            resume.setQrcode(data);
            UpdateWrapper<Resume> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            resumeService.update(resume, wrapper);
            return Result.success("二维码上传成功");
        } catch (Exception e) {
            return Result.error("二维码传失败");
        }
    }
}

